'''
Created on Jul 16, 2013

@author: loic
'''

import MySQLdb

class tvdb(object):
	'''
	classdocs
	'''


	def __init__(self):
		'''
		Constructor
		'''
		self.db = MySQLdb.connect('localhost', 'loic', 'brad01', 'tvprogfr')
		self.cur = self.db.cursor(MySQLdb.cursors.DictCursor)

	def close(self):
		self.db.close()

	def get_any(self, *args, **kwargs):
		table=args[0]
#		print 'Table = '+table, kwargs
		query = []
		fields = []
		for key, value in kwargs.iteritems():
			query.append('{0} = %s'.format(key))
			fields.append(value)
		q = 'select * from {0} where '.format(table)+' and '.join(query)
		print q, query, fields
		self.cur.execute(q, fields)
		return self.cur.fetchall()

	def get_channel(self, **kwargs):
		return self.get_any('channel')

	def add_channel(self, id, nb, name):
		rows = self.get_channel(id=id, nb=nb)
		if len(rows) == 0:
			query = 'insert into channels set id=%s, nb=%s, name=%s'
			self.cur.execute(query, (id, nb, name))
			self.db.commit()
			rows = self.get_channel(id=id, nb=nb)
			return self.cur.lastrowid
		else:
			return rows['idchannels']

	def get_serie(self, **kwargs):
		return self.get_any('serie', kwargs)

	def add_serie(self, banned=None, followed=None):
		param_names = []
		param_values = []
		param_names.append('banned=%s')
		if banned:
			param_values.append(1)
		else:
			param_values.append(0)
		if followed:
			param_names.append('followed=%s')
			param_values.append(1)
		query = 'insert into series'# set title=%s'
		if len(param_names)>0:
			query += ' set '+ ', '.join(param_names)
		print query
		self.cur.execute(query, param_values)
		self.db.commit()
		return self.cur.lastrowid


	def get_title(self, **kwargs):
		print kwargs
		return self.get_any('titles', **kwargs)

	def add_title(self, title, idserie):
		rows = self.get_title(title=title)
		if len(rows) == 0:
			query = 'insert into titles set title=%s, series_idseries=%s'
			self.cur.execute(query, (title, idserie))
			self.db.commit()
			return self.cur.lastrowid
		else:
			return rows['idtitles']


